package com.winning.vsts.merge.service.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.eventbus.EventBus;
import com.winning.vsts.merge.service.configuration.VstsContext;
import com.winning.vsts.merge.service.constant.BranchNameEnum;
import com.winning.vsts.merge.service.domain.PullRequest;
import com.winning.vsts.merge.service.domain.VstsProject;
import com.winning.vsts.merge.service.domain.VstsUser;
import com.winning.vsts.merge.service.entity.PullRequestDO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;
import java.util.Set;

/**
 * 抽象实现
 *
 * @author xcl <xcl@winning.com.cn>
 * @date 2020/3/18
 */
@Component
public abstract class BasePullRequestService implements PullRequestService {

    private final static Logger logger = LoggerFactory.getLogger(BasePullRequestService.class);

    @Autowired
    protected VstsClient vstsClient;

    @Autowired
    protected VstsContext vstsContext;

    @Autowired
    protected RecordPullRequestService recordPullRequestService;

    @Autowired
    private EventBus eventBus;

    @Override
    public void pullRequest(RestTemplate restTemplate, VstsProject vstsProject, String sourceBranch,
                            String targetBranch, String pullNo) {
        // 进行必要的检查
        boolean checkFlag = checkBranch(vstsProject, sourceBranch, targetBranch);
        if (!checkFlag) {
            return;
        }
        // 创建PR请求
        PullRequestDO pullRequest =
            vstsClient.getPullRequestParam(restTemplate, vstsProject, sourceBranch, targetBranch);
        pullRequest.setPullNo(pullNo);
        // 保存请求信息
        PullRequest record = recordPullRequestService.savePullRequest(pullRequest);

        // 比较两个分支，获取到对应的commitId
        int commitCount = pullRequest.getCommitCount();
        int prCommitCount = pullRequest.getPrCommitCount();
        /*if (commitCount <= 0) {
            logger.info("项目{}无提交信息,不进行合并", vstsProject.getProjectName());
            return;
        }*/
/*        if (commitCount == prCommitCount) {
            logger.info("项目{}全是PR提交信息,不进行合并", vstsProject.getProjectName());
            return;
        }*/
        Set<String> worksItemIds = pullRequest.getWorksItemIds();
/*        if(!targetBranch.equals(BranchNameEnum.DEVELOP.getValue())){
            int size = worksItemIds.size();
            if (size <= 0) {
                logger.warn("项目{}没有工作项信息，其中commitCount:{},prCommitCount:{},不进行合并",
                        vstsProject.getProjectName(), commitCount, prCommitCount);
                return;
            }
        }*/
        if(Objects.isNull(worksItemIds)){
            logger.warn("所选分支之间没有要合并的更改。");
            return;
        }

        JSONObject request = pullRequest.getRequest();
        // 是否创建中间分支合并
        String middleBranch = createBranchIfNecessary(restTemplate, vstsProject, sourceBranch, targetBranch);
        // 创建了中间分支，需要调整原分支
        if (StringUtils.hasLength(middleBranch)) {
            request.put("sourceRefName", middleBranch);
        }
        // 创建PR请求
        JSONObject prResult = vstsClient.createPullRequest(restTemplate, vstsProject, request, worksItemIds);
        recordPullRequestService.updatePullRequestStatus(record.getId(), prResult);
        //// 请求ID
        String pullRequestId = prResult.getString("pullRequestId");
        pullRequest.setPullRequestId(pullRequestId);
        try {
            boolean deleteFlag = isDeleteSourceBranch();
            // 设置自动完成,可能因为权限问题，自动完成失败
            VstsUser vstsUser = vstsContext.vstsUser(vstsProject);
            String userID = vstsUser.getVstsId();
            vstsClient.setAutoComplete(restTemplate, vstsProject, pullRequestId, userID, deleteFlag);
        } catch (Exception e) {
            logger.error("项目:{}设置自动完成失败:{}", vstsProject.getProjectName(), e.getMessage());
        }
        try {
            // 自动审批,可能因为权限问题，自动审批失败
            autoApprove(restTemplate, vstsProject, pullRequestId);
        } catch (Exception e) {
            logger.error("项目:{}自动审批失败:{}", vstsProject.getProjectName(), e.getMessage());
        }
        // 发布工作项事件
        eventBus.post(pullRequest);
    }

    /**
     * 自动审批
     *
     * @param restTemplate  请求
     * @param vstsProject   项目信息
     * @param pullRequestId pull request id
     */
    protected void autoApprove(RestTemplate restTemplate, VstsProject vstsProject, String pullRequestId) {

    }

    /**
     * 是否删除原分支
     *
     * @return true 删除 false 不删除
     */
    protected abstract boolean isDeleteSourceBranch();

    /**
     * 是否需要创建中间分支
     *
     * @param restTemplate 请求
     * @param vstsProject  项目信息
     * @param sourceBranch 原分支
     * @param targetBranch 目标分支
     * @return 创建新的中间的分支
     */
    protected String createBranchIfNecessary(RestTemplate restTemplate, VstsProject vstsProject, String sourceBranch,
                                             String targetBranch) {
        return null;
    }


    protected boolean checkIfNecessary(String sourceBranch) {
        return !sourceBranch.startsWith("feature") && !sourceBranch.startsWith("issue")
            && !sourceBranch.startsWith("bugfix") && !sourceBranch.startsWith("hotfix");
    }


    protected boolean checkBranch(VstsProject vstsProject, String sourceBranch, String targetBranch) {
        return true;
    }
}
